package com.xz.group12306.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.xz.group12306.business.service.impl.TicketServiceImpl;
import com.xz.group12306.domain.Cart;
import com.xz.group12306.domain.Ticket;
import com.xz.group12306.domain.User;

/**
 * @author 胡晨倩
 */
@WebServlet("/BuyTicketServlet")
public class BuyTicketServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public BuyTicketServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		// 修改乱码
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		TicketServiceImpl ticketServiceImpl=new TicketServiceImpl();
	
		Ticket ticket=(Ticket) request.getSession().getAttribute("ticket");
		User user=(User) request.getSession().getAttribute("user");
		
		if(ticket.getTicketNo()>0) {
		ticketServiceImpl.updateTicket(ticket.getTicketId());
		//增加记录
		Cart cart=new Cart();
		cart.setUserid(user.getId());
		cart.setTicketid(ticket.getTicketId());
		cart.setDepature(ticket.getDepature());
		cart.setDestinction(ticket.getDestinction());
		cart.setCostTime(ticket.getCostTime());
		cart.setStartTime(ticket.getStartTime());
		cart.setTrainNo(ticket.getTrainNo());
		ticketServiceImpl.addCart(cart);
		response.getWriter().print("<script>alert(\"购买成功\");</script>");
		}else {
			response.getWriter().print("<script>alert(\"购买失败，余票不足\");</script>");
		}
		
		
	}

}
